package edu.bw.dao.Impl;

import edu.bw.dao.ProductDao;
import edu.bw.mapper.ProductMapper;
import edu.bw.po.Product;
import lombok.Setter;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

@Setter
@Repository
public class ProductDaoImpl implements ProductDao {

 /*   @Autowired
    private QueryRunner queryRunner;*/

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public void saveProduct(Product product) {
        jdbcTemplate.update("INSERT INTO spring.product(pname,price,category) VALUES (?,?,?)",
                product.getPname(),product.getPrice(),product.getCategory());

    }

    @Override
    public void updateProduct(Product product) {

            /*queryRunner.update("UPDATE spring.product SET pname=?,price=?,category=? WHERE pid=?",
                    product.getPname(),product.getPrice(),product.getCategory(),product.getPid());
            */
        jdbcTemplate.update("UPDATE spring.product SET pname=?,price=?,category=? WHERE pid=?",
                product.getPname(), product.getPrice(), product.getCategory(), product.getPid());
    }

    @Override
    public void deleteProduct(Integer pid) {
        jdbcTemplate.update("DELETE FROM spring.product WHERE pid=?",pid);
    }

    @Override
    public List<Product> findAll() {
/*        try {
            *//*return queryRunner.query("SELECT * FROM spring.product",
                    new BeanListHandler<Product>(Product.class));*//*
            jdbcTemplate.query("SELECT * FROM spring.product", );

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        */

        return jdbcTemplate.query("SELECT * FROM spring.product ",productMapper);
    }

    @Override
    public Product findById(Integer pid) {

        /**
         * 第一个参数:SQL语句
         * 第二个参数:结果集类型
         * 第三个参数:?占位符对应的值
         */
        return jdbcTemplate.queryForObject("SELECT * FROM spring.product WHERE pid=?",
                productMapper,pid);

    }



}
